import React from 'react';
import { connect } from 'react-redux';
import { messages, deepFullCopy, queryCurrencyPrecision } from 'share/common'
import { Button, message, Modal, Popover, Row, Col, Tag, Table } from 'antd';
import errorMessage from 'share/errorMessage'
import expenseRecordService from 'containers/expense-record/expense-record.service'
import ResizeTable from "components/resize-table"
import moment from 'moment'
import 'styles/expense-record/refund-modal-result.scss'

class RefundModal extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      currentData: {},
      page: 0,
      pageSize: 5,
      pagination: {
        total: 0
      },
      loading: false,
      data: [],  //可关联的还款单列表
      columns: [
        {
          title: messages('request-5.key24')/*还款日期*/, dataIndex: 'createDate', width: 120,
          render: (value, record) => moment(value).format('YYYY-MM-DD')
        },
        {
          title: messages('request-5.key25')/*还款单号*/, dataIndex: 'businessCode',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('common.currency')/*币种*/, dataIndex: 'curreny', width: 60
        },
        {
          title: messages('common.amount')/*金额*/, dataIndex: 'actRepayAmount',
          render: (value, record) => this.filterMoney(value, queryCurrencyPrecision(record.curreny))
        },
        {
          title: messages('request-5.key26')/*事由*/, dataIndex: 'remark',
          render: value => value ? <Popover placement="topLeft" content={value}>{value}</Popover> : '-'
        },
        {
          title: messages('request-5.key27')/*还款方式*/, dataIndex: 'type',
          render: value => <span>{messages('request-5.key28')/*额度还款*/}</span>
        },
      ],
      selectedRowKeys: [],
      selectedRows: [],
      //selectedTotalAmount需 <= recordTotalAbsAmount
      recordTotalAbsAmount: 0, //当前消费记录总金额的绝对值
      selectedTotalAmount: 0, //当前选中的还款单的金额合计
      submitLoading: false
    }
  }

  componentWillMount() {};

  componentWillReceiveProps(nextProps) {
    const { visible } = this.props;
    if (!visible && nextProps.visible) {
      this.setState({
        recordTotalAbsAmount: Math.abs(nextProps.recordData.amount),
        currentData: nextProps.recordData
      }, () => {
        this.initSelected(); //初始化已选中的数据
        this.getList();
      });
    }
    //关闭modal后的操作
    if (visible && !nextProps.visible) {
      //还原数据
      this.setState({
        page: 0,
        pageSize: 5,
        pagination: {
          total: 0
        },
        selectedRowKeys: [],
        selectedRows: [],
        recordTotalAbsAmount: 0,
        selectedTotalAmount: 0
      });
    }
  };

  initSelected = () => {
    const { currentData } = this.state;
    let selectedRows = [];
    let selectedRowKeys = [];
    if (currentData.refRepaymentList) {
      currentData.refRepaymentList.map(item => {
        selectedRowKeys.push(item.businessCode);
        selectedRows.push({
          id: item.id,
          businessCode: item.businessCode,
          currency: item.curreny,
          amount: item.actRepayAmount
        });
      });
      this.setState({selectedRows, selectedRowKeys}, this.refreshAmount);
    }
  };

  //刷新selectedTotalAmount的值
  refreshAmount = () => {
    const { selectedRows } = this.state;
    let selectedTotalAmount = 0;
    selectedRows.map(item => {
      selectedTotalAmount += item.amount;
    });
    this.setState({selectedTotalAmount});
  };

  getList = () => {
    const { currentData, page, pageSize, pagination } = this.state;
    const { user } = this.props;
    let params = {};
    //params.applicantOid = currentData.userOID; //为了mock数据先注释了
    params.applicantOid = user.userOID; //为了mock数据先用登录人的
    params.currency = currentData.currencyCode;
    params.companyOid = currentData.companyOID;
    //params.repaymentType = 4;  //为了mock数据先注释了
    params.page = page;
    params.size = pageSize;
    this.setState({loading: true});
    expenseRecordService.getRefundList(params).then(res => {
      pagination.total = Number(res.headers['x-total-count']) || 0;
      pagination.current = page + 1;
      this.setState({
        pagination,
        loading: false,
        data: res.data
      });
    }).catch(err => {
      errorMessage(err.response);
      this.setState({loading: false});
    });
  };

  handleTableChange = (pagination) => {
    let page = pagination.current;
    this.setState({
      page: page - 1
    }, this.getList);
  };

  handleOk = () => {
    const { selectedRows, currentData } = this.state;
    let params = {
      bankOrderId: currentData.id,
      repaymentIds: []
    };
    selectedRows && selectedRows.map(item => {
      params.repaymentIds.push(item.id);
    });
    this.setState({submitLoading: true});
    expenseRecordService.setRefundRelate(params).then(res => {
      this.setState({submitLoading: false});
      message.success(messages('common.save.success',{arg1: ''})/*{arg1} 保存成功*/);
      this.props.onOk();
    }).catch(err => {
      errorMessage(err.response);
      this.setState({submitLoading: false});
    });
  };

  handleCancel = () => {
    this.props.onCancel();
  };

  //列表选择更改
  onSelectChange = (selectedRowKeys) => {
    this.setState({selectedRowKeys});
  };

  refreshSelectedRowKeys = () => {
    const { selectedRows } = this.state;
    let selectedRowKeys = [];
    selectedRows.map(item => {
      selectedRowKeys.push(item.businessCode);
    });
    this.setState({selectedRowKeys});
  };

  //选择一行
  //选择逻辑：每一项设置selected属性，如果为true则为选中
  onSelectRow = (record, selected) => {
    const { recordTotalAbsAmount, selectedTotalAmount } = this.state;
    if (selected && selectedTotalAmount + record.actRepayAmount > recordTotalAbsAmount) {
      message.error(messages('request-5.key29')/*关联还款单的总金额不能超过本消费记录的金额。*/);
      this.refreshSelectedRowKeys();
      return;
    }
    let selectedRows = deepFullCopy(this.state.selectedRows);
    let item = {
      id: record.id,
      businessCode: record.businessCode,
      currency: record.curreny,
      amount: record.actRepayAmount
    };
    selected ? selectedRows.addIfNotExistObj(item, 'businessCode') : selectedRows.deleteObj(item, 'businessCode');
    this.setState({selectedRows}, this.refreshAmount);
  };

  removeValue = (e, item) => {
    e.preventDefault();
    let { selectedRows, selectedRowKeys } = this.state;
    selectedRows.deleteObj(item, 'businessCode');
    selectedRowKeys.delete(item.businessCode);
    this.setState({selectedRows, selectedRowKeys}, this.refreshAmount);
  };

  render() {
    const { visible } = this.props;
    const { columns, loading, data, pagination, selectedRowKeys, selectedRows, selectedTotalAmount, submitLoading } = this.state;
    const rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
      onSelect: this.onSelectRow
    };
    return (
      <Modal
        title={messages('request-5.key30')/*关联还款单*/}
        visible={visible}
        onOk={this.handleOk}
        confirmLoading={submitLoading}
        onCancel={this.handleCancel}
        width={"800px"}
        wrapClassName="refund-modal-result"
      >
        <div className="modal-content">
          <Row className="margin-bottom-15" style={{lineHeight: '30px'}}>
            {messages('request-5.key31')/*已选择*/}：
            {selectedRows.map((item, index) => {
              return (
                <Tag closable onClose={(e) => this.removeValue(e, item)}>
                  {item.businessCode}
                </Tag>
              )
            })}
          </Row>
          <Row className="margin-bottom-15">
            {messages('request-5.key32')/*合计金额*/}:
            CNY&nbsp;{this.filterMoney(selectedTotalAmount, 2)}
          </Row>
          <Table
            columns={columns}
            loading={loading}
            dataSource={data}
            rowSelection={rowSelection}
            size="middle"
            bordered
            rowKey="businessCode"
            pagination={pagination}
            onChange={this.handleTableChange}
          />
        </div>
      </Modal>
    )
  }
}

RefundModal.propTypes = {
  onCancel: React.PropTypes.func,
  visible: React.PropTypes.bool,  //对话框是否可见
  onOk: React.PropTypes.func,  //点击OK后的回调
  recordData: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    languageList: state.login.languageList,
    user: state.login.user //mock数据用
  }
}

export default connect(mapStateToProps)(RefundModal)
